<template>
  <div>
    <el-dialog :title="title"
               :visible.sync="visible"
               v-loading="loading"
               :before-close="modalClose"
               :close-on-click-modal="false"
               :close-on-press-escape="false"
               width="80%">
      <el-form :model="formdata"
               label-position="right"
               ref="formdataRef"
               label-width="150px"
               :rules='formdataRules'>
        <el-form-item label="服务名称："
                      prop="fetalHeartRate.name">
          <el-input placeholder="请输入服务名称"
                    maxlength="20"
                    show-word-limit
                    v-model="formdata.fetalHeartRate.name"
                    clearable
                    class="w-200"></el-input>
        </el-form-item>
        <el-form-item label="所属医院："
                      prop="fetalHeartRate.hospitalId">
          <el-select v-model="formdata.fetalHeartRate.hospitalId"
                     clearable
                     class="w-200"
                     placeholder="请选择所属医院">
            <el-option v-for="item in hospitalList"
                       :key="item.id"
                       :label="item.name"
                       :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="适用人群："
                      prop="fetalHeartRate.users">
          <el-input placeholder="请输入适用人群"
                    v-model="formdata.fetalHeartRate.users"
                    class="w-200"></el-input>
        </el-form-item>
        <el-form-item label="价格："
                      prop="fetalHeartRate.price">
          <el-input-number v-model="formdata.fetalHeartRate.price"
                           :min="0"
                           :precision="2"
                           placeholder="请输入价格"
                           :controls="true"
                           class="w-200"></el-input-number>
          <span class="unit">元</span>
        </el-form-item>

        <el-form-item label="慢病签约服务费标准：">
          <el-input-number v-model="formdata.fetalHeartRate.cdpFee"
                           :min="0"
                           :precision="2"
                           placeholder="请输入慢病签约服务费标准"
                           :controls="true"
                           class="w-200"></el-input-number>
          <span class="unit">元</span>
        </el-form-item>

        <el-form-item label="解读数据条数："
                      prop="fetalHeartRate.totalNumHeart">
          <el-input-number v-model="formdata.fetalHeartRate.totalNumHeart"
                           :min="0"
                           placeholder="请输入解读数据条数"
                           :controls="true"
                           class="w-200"></el-input-number>
          <span class="unit">条</span>
        </el-form-item>
        <el-form-item label="解读频率："
                      prop="fetalHeartRate.frequency">
          <el-input-number v-model="formdata.fetalHeartRate.frequency"
                           :min="0"
                           placeholder="请输入解读频率"
                           :controls="true"
                           class="w-200"></el-input-number>
          <span class="unit">条</span>
        </el-form-item>
        <el-form-item label="有效期："
                      prop="fetalHeartRate.termOfValidity">
          <el-input-number v-model="formdata.fetalHeartRate.termOfValidity"
                           :min="0"
                           placeholder="请输入有效期"
                           :controls="true"
                           class="w-200"></el-input-number>
          <span class="unit">天</span>
        </el-form-item>
        <el-form-item label="列表图片："
                      prop="fetalHeartRate.listImgUrl">
          <el-upload class="avatar-uploader"
                     :action="imageUploadUrl"
                     :show-file-list="false"
                     accept=".JPG, .PNG, .JPEG,.jpg, .png, .jpeg"
                     :on-success="handleAvatarSuccess"
                     :before-upload="beforeAvatarUpload">
            <img v-if="formdata.fetalHeartRate.listImgUrl"
                 :src="formdata.fetalHeartRate.listImgUrl"
                 class="avatar">
            <i v-else
               class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="详情图片："
                      prop="fetalHeartRate.detailsImgUrl">
          <el-upload multiple
                     :limit=limitImgNum
                     :action="imageUploadUrl"
                     accept=".JPG, .PNG, .JPEG,.jpg, .png, .jpeg"
                     list-type="picture-card"
                     :on-success="handlePictureCardPreview"
                     :file-list='formdata.fetalHeartRate.detailsImg'
                     :on-exceed='onexceed'
                     :on-remove='onremove'
                     :before-upload="beforeAvatarUpload">
            <i class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="服务简介："
                      prop="fetalHeartRate.serviceProfile">
          <el-input v-model="formdata.fetalHeartRate.serviceProfile"
                    :min="0"
                    placeholder="请输入服务简介"
                    type="textarea"
                    style="width:50%"></el-input>
        </el-form-item>
        <el-form-item label="特别告知："
                      prop="fetalHeartRate.inform">
          <el-input v-model="formdata.fetalHeartRate.inform"
                    :min="0"
                    placeholder="请输入特别告知"
                    type="textarea"
                    style="width:50%"></el-input>
        </el-form-item>
        <el-form-item label="医学知识：">
          <el-button type="success"
                     @click="handleAddRow(1)">新 增 一 项</el-button>
          <el-table :data="formdata.heartMedicalKnowledge"
                    class="mt-20"
                    border
                    show-header>
            <el-table-column label="项目名称">
              <template slot-scope="scoped">
                <el-form-item :rules="listRules.name"
                              :prop="'heartMedicalKnowledge.' + scoped.$index + '.name'">
                  <el-input v-model="scoped.row.name"
                            maxlength="50"
                            autocomplete="off"
                            class="w-200"
                            placeholder="请输入项目名称"></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="clinicalSignificance"
                             label="临床意义">
              <template slot-scope="scoped">
                <el-form-item :rules="listRules.clinicalSignificance"
                              :prop="'heartMedicalKnowledge.' + scoped.$index + '.clinicalSignificance'">
                  <el-input v-model="scoped.row.clinicalSignificance"
                            maxlength="500"
                            :rows="4"
                            type="textarea"
                            autocomplete="off"
                            show-word-limit
                            placeholder="请输入临床意义"></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="address"
                             label="图片"
                             width="150"
                             align="center">
              <template slot-scope="scoped">
                <el-form-item :rules="listRules.knowledgeImgUrl"
                              :prop="'heartMedicalKnowledge.' + scoped.$index + '.knowledgeImgUrl'">
                  <div @click="op(scoped.$index)">
                    <el-upload class="avatar-uploader"
                               :action="imageUploadUrl"
                               :show-file-list="false"
                               accept=".JPG, .PNG, .JPEG,.jpg, .png, .jpeg"
                               :on-success="heartMedicalKnowledgeSuccess"
                               :before-upload="beforeAvatarUpload">
                      <img v-if="scoped.row.knowledgeImgUrl"
                           :src="scoped.row.knowledgeImgUrl"
                           class="avatar">
                      <i v-else
                         class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                  </div>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="address"
                             label="操作"
                             width="100">
              <template slot-scope="scoped">
                <el-button type="text"
                           @click='deleteTable(scoped.$index, formdata.heartMedicalKnowledge)'>删 除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item label="医学知识链接："
                      prop="heartMedicalKnowledgeLink">
          <el-button type="success"
                     @click="handleAddRow(2)">新 增 一 项</el-button>
          <el-table :data="formdata.heartMedicalKnowledgeLink"
                    class="mt-20"
                    border>
            <el-table-column prop="title"
                             label="链接标题">
              <template slot-scope="scoped">
                <el-form-item :rules="listRules.title"
                              :prop="'heartMedicalKnowledgeLink.' + scoped.$index + '.title'">
                  <el-input v-model="scoped.row.title"
                            maxlength="50"
                            autocomplete="off"
                            placeholder="请输入链接标题"></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="link"
                             label="链接">
              <template slot-scope="scoped">
                <el-form-item :rules="listRules.link"
                              :prop="'heartMedicalKnowledgeLink.' + scoped.$index + '.link'">
                  <el-input v-model="scoped.row.link"
                            type="textarea"
                            maxlength="500"
                            :rows="4"
                            autocomplete="off"
                            show-word-limit
                            placeholder="请输入链接"></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="address"
                             label="操作"
                             width="100">
              <template slot-scope="scoped">
                <el-button type="text"
                           @click='deleteTable(scoped.$index, formdata.heartMedicalKnowledgeLink)'>删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item label="推广分成：">
          <el-input-number :min="0"
                           clearable
                           :precision="2"
                           :controls="false"
                           v-model="formdata.fetalHeartRate.share"
                           placeholder="非必填"
                           class="w-200"></el-input-number>
        </el-form-item>
        <el-form-item label="购买服务后，是否填写健康服务号："
                      label-width="240px">
          <el-radio-group v-model="formdata.fetalHeartRate.isInvitationCode">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否支持退款：">
          <el-radio-group v-model="formdata.fetalHeartRate.refund">
            <el-radio :label="0">可退款</el-radio>
            <el-radio :label="1">不可退款</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item>
          <el-button @click="modalClose">取 消</el-button>
          <el-button type="primary"
                     @click="onSubmit">保 存</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
  export default {
    name: '', // 胎心解读管理弹窗
    props: {
      fetalHeartObj: {
        type: Object,
        default: {}
      },
      visible: {
        type: Boolean,
        default: false
      },
      getList: {
        type: Function,
        default: null
      },
      isDetail: {
        type: Boolean,
        default: false
      }
    },
    data () {
      return {
        title: '新 增',
        loading: false,
        limitImgNum: 6,
        formdata: {
          fetalHeartRate: {
            id: null,
            name: '',
            hospitalId: '',
            price: '',
            totalNumHeart: '', // 解读数据条数
            frequency: '', // 解读频率
            termOfValidity: '', // 有效期
            listImgUrl: '', // 列表图片
            detailsImgUrl: [], // 详情图片
            detailsImg: [],
            serviceProfile: '', // 服务简介
            inform: '', // 特别告知
            share: 0, // 推广分成
            refund: 0, // 是否支持退款
            users: '', // 适用人群
            isInvitationCode: 0, // 健康服务号
            cdpFee: '', // 健康服务号
          },
          heartMedicalKnowledge: [
            {
              id: null,
              name: '',
              knowledgeImgUrl: '', // 医学知识图片
              clinicalSignificance: '', // 临床意义
            }
          ],
          heartMedicalKnowledgeLink: [
            {
              id: null,
              title: '',
              link: '',
            }
          ],
        },
        whichImg: 0,
        // imageUploadUrl: this.api.file.upload,
        imageUploadUrl: this.api.appUpgradeUpload.url,
        formdataRules: {
          'fetalHeartRate.name': [
            { required: true, message: '请输入服务名称', trigger: 'blur' }
          ],
          'fetalHeartRate.hospitalId': [
            { required: true, message: '请选择所属医院', trigger: ['change', 'blur'] }
          ],
          'fetalHeartRate.users': [
            { required: true, message: '请输入适用人群', trigger: 'blur' }
          ],
          'fetalHeartRate.price': [
            { required: true, message: '请输入价格', trigger: 'blur' }
          ],
          'fetalHeartRate.totalNumHeart': [
            { required: true, message: '请输入解读数据条数', trigger: 'blur' }
          ],
          'fetalHeartRate.frequency': [
            { required: true, message: '请输入解读频率', trigger: 'blur' }
          ],
          'fetalHeartRate.termOfValidity': [
            { required: true, message: '请输入有效期', trigger: 'blur' }
          ],
          'fetalHeartRate.listImgUrl': [
            { required: true, message: '请上传列表图片', trigger: ['change', 'blur'] }
          ],
          'fetalHeartRate.detailsImgUrl': [
            { required: true, message: '请上传详情图片', trigger: ['change', 'blur'] }
          ],
          'fetalHeartRate.serviceProfile': [
            { required: true, message: '请输入服务简介', trigger: 'blur' }
          ],
          'fetalHeartRate.inform': [
            { required: true, message: '请输入特别告知', trigger: 'blur' }
          ]
        },
        listRules: {
          name: [{ required: true, message: '请输入项目名称', trigger: ['blur', 'change'] }],
          clinicalSignificance: [{ required: true, message: '请输入临床意义', trigger: 'blur' }],
          knowledgeImgUrl: [{ required: true, message: '请上传医学知识图片', trigger: ['blur', 'change'] }],
          title: [{ required: true, message: '请输入链接标题', trigger: 'blur' }],
          link: [{ required: true, message: '请输入链接', trigger: 'blur' }],
        },
        hospitalList: []
      }
    },
    methods: {
      modalClose () {
        this.$emit('update:visible', false); // 直接修改父组件的属性
      },
      // 所属医院
      async selectHospital () {
        const { data: res } = await this.post(this.api.fetaHeart.selectHeartRateHospitalList, {
          serviceType: 3
        })
        if (res.code === '200') {
          this.hospitalList = res.object;
        }

      },
      // 动态添加行
      handleAddRow (index) {
        switch (index) {
          case 1:
            this.formdata.heartMedicalKnowledge.push({
              id: null,
              name: '',
              knowledgeImgUrl: '', // 医学知识图片
              clinicalSignificance: '', // 临床意义
            })
            break
          case 2:
            this.formdata.heartMedicalKnowledgeLink.push({
              id: null,
              title: '',
              link: '',
            })
            break
        }
      },
      op (index) {
        this.whichImg = index;
      },
      // 医学知识
      heartMedicalKnowledgeSuccess (res) {
        this.formdata.heartMedicalKnowledge.forEach((ele, index) => {
          if (this.whichImg == index) {
            this.$set(ele, 'knowledgeImgUrl', res.object[0]);
          }
        })
      },
      // 列表图片地址
      handleAvatarSuccess (res) {
        this.formdata.fetalHeartRate.listImgUrl = res.object[0];
      },
      beforeAvatarUpload (file) {
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isLt2M) {
          this.$message.error('上传图片大小不能超过 2MB!');
        }
        return isLt2M;
      },
      // 详情图片地址
      handlePictureCardPreview (res) {
        this.formdata.fetalHeartRate.detailsImgUrl.push(res.object[0]);
      },
      onremove (res, list) {
        if (res.response) {
          this.formdata.fetalHeartRate.detailsImgUrl = this.formdata.fetalHeartRate.detailsImgUrl.filter(ele => ele != res.response.object[0]);
        } else {
          this.formdata.fetalHeartRate.detailsImgUrl = this.formdata.fetalHeartRate.detailsImgUrl.filter(ele => ele != res.url);
        }
      },
      onexceed () {
        this.$message.warning('详情图片至多上传6张');
      },
      onSubmit () {
        this.$refs.formdataRef.validate((valid) => {
          if (valid) {
            if (this.formdata.fetalHeartRate.share >= this.formdata.fetalHeartRate.price) {
              this.$message.error('推广费不能大于或等于套餐价格!');
              return
            }
            let { detailsImg, ...params } = this.formdata.fetalHeartRate;
            params.detailsImgUrl = JSON.stringify(params.detailsImgUrl);
            params.share = params.share != undefined ? params.share : 0;
            this.post(this.api.fetaHeart.addOrUpdate, {
              heartMedicalKnowledge: this.formdata.heartMedicalKnowledge,
              heartMedicalKnowledgeLink: this.formdata.heartMedicalKnowledgeLink,
              fetalHeartRate: params
            }).then(({ data }) => {
              if (data.code === '200') {
                this.modalClose();
                this.$parent.getList(); // 调用父件组方法
                this.$message.success('保存成功!');
              }
            })
          }
        })
      },
      // 动态删除数据
      deleteTable (index, table) {
        if (table.length == 1) {
          this.$message.warning('至少保留一项');
          return
        } else {
          table.splice(index, 1);
        }
      },
      // 查询详情
      async getDetail () {
        const { data: res } = await this.post(this.api.fetaHeart.getFetalHeartRateServiceInfo, {
          heartRateId: this.fetalHeartObj.id
        })
        if (res.code === '200') {
          let resData = res.object
          this.formdata.fetalHeartRate = resData.fetalHeartRate;
          this.formdata.fetalHeartRate.detailsImgUrl = JSON.parse(this.formdata.fetalHeartRate.detailsImgUrl);
          this.formdata.fetalHeartRate.detailsImg = [];
          this.formdata.fetalHeartRate.detailsImgUrl.forEach(ele => {
            let op = {};
            op.name = ele;
            op.url = ele;
            this.formdata.fetalHeartRate.detailsImg.push(op);
          })
          this.formdata.heartMedicalKnowledge = resData.heartMedicalKnowledge;
          this.formdata.heartMedicalKnowledgeLink = resData.heartMedicalKnowledgeLink;
        }

      }
    },
    created () {
      if (this.fetalHeartObj) {
        this.getDetail(); // 查询详情
        this.title = '编 辑';
      }
      this.selectHospital();
    },
  }
</script>
<style scoped lang="scss">
  .el-upload-list--picture-card .el-upload-list__item {
    width: 98px !important;
    height: 98px !important;
  }
  .el-upload--picture-card {
    width: 98px !important;
    height: 98px !important;
    line-height: 98px !important;
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 98px !important;
    height: 98px !important;
    line-height: 98px !important;
    text-align: center;
  }
  .avatar {
    width: 98px !important;
    height: 98px !important;
    display: block;
  }
  .unit {
    padding-left: 10px;
  }
</style>
